#pragma once
#include<functional>
#include<signal.h>
#include"Log.hpp"
#include"Socket.hpp"

using func_t = std::function<std::string (std::string &package)>;

class TcpServer
{
public:
    TcpServer(uint16_t port, func_t callback)
    :_port(port)
    ,_callback(callback)
    {}

    bool InitServer()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
        return true;
    }
    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);
        while(true)
        {
            string clientip;
            uint16_t clientport;
            int sockfd = _listensock.Accept(&clientip, &clientport);
            if(sockfd < 0) continue;
            //serve
            if(fork() == 0)
            {
                _listensock.Close();
                std::string resq_stream;
                while(true)
                {
                    char buffer[128];
                    ssize_t n = read(sockfd, buffer, sizeof(buffer));
                    if(n > 0)
                    {
                        buffer[n] = 0;
                        resq_stream += buffer;
                        std::string info = _callback(resq_stream);;

                    }
                }

                exit(0);
            }
            close(sockfd);
        }
    }
private:
    uint16_t _port;
    Sock _listensock;
    func_t _callback;
};